<?php

namespace App\Http\Controllers;

use App\Http\Requests\LbtAddRequest;
use App\Http\Requests\LoginRequest;
use App\Models\Admin;
use App\Models\File;
use App\Models\System;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Mews\Captcha\Facades\Captcha;
use ZipArchive;

class SystemController extends Controller
{

    public function login(LoginRequest $loginRequest){
        $data = [
            'username' =>  $loginRequest->post('username',''),
            'pwd' =>  $loginRequest->post('pwd',''),
            'captcha' => $loginRequest->post('captcha',''),
            'ck' => $loginRequest->post('ck','')
        ];
        if (!captcha_api_check($data['captcha'] , $data['ck'])){
            cp_return(__('message.captcha_error'));
        }
        $token = md5(md5(time()));
        $adminModel = (new Admin());
        $userInfo = $adminModel->where('username',$data['username'])->first();
        if(!$userInfo){
            cp_return(__('message.login_error'));
        }


        if (!Hash::check($data['pwd'], $userInfo->pwd)) {
            cp_return(__('message.login_error'));
        }

        // 检查键是否已存在
        if (Redis::exists('admin:token')) {
            // 如果键已存在，则更新过期时间
            Redis::pexpire('admin:token', 24 * 60 * 60 * 1000);
            return c_return(0,[
                'token' => Redis::get('admin:token')
            ]);
        } else {
            // 如果键不存在，则设置新的键值并设置过期时间
            Redis::psetex('admin:token', 24 * 60 * 60 * 1000, $token);
        }
        return c_return(0,[
            'token' => $token
        ]);
    }

    public function getCaptcha(){
        return c_return(0,Captcha::create('default',true));
    }


    public function mapType(){
        return c_return(0,[
            [
                'name' => '咨询',
                'value' => 1,
                'key' =>1
            ],
            [
                'name' => '游戏资讯',
                'value' => 2,
                'key' =>2
            ]
        ]);
    }

    public function mapLang(){
        return c_return(0,[
            [
                'name' => '英文en',
                'value' => 1,
                'key' =>1
            ],
            [
                'name' => '中文zh',
                'value' => 2,
                'key' =>2
            ]
        ]);
    }

    public function osSelect(){
        return c_return(0,[
            [
                'name' => 'Android',
                'value' => 1,
                'key' =>1
            ],
            [
                'name' => 'IOS',
                'value' => 2,
                'key' =>2
            ]
        ]);
    }
    public function listStyleSelect(){
        return c_return(0,[
            [
                'name' => '样式_playmanygames',
                'value' => 1,
                'key' =>1
            ],
            [
                'name' => '样式_hotplaying',
                'value' => 2,
                'key' =>2
            ]
        ]);
    }

    public function pushGame(){
        // 默认读取最新的文件
        $fileModel = new File();
        $file = $fileModel->orderBy('id','desc')->first()->toArray();
        $files = $fileModel->select(['id','file_path'])->where('id','!=',$file['id'])->get()->toArray();
        if($files){
            $gameZipDirPath =  Storage::path('public/');
            foreach ($files as $vFile){
                if(is_file($gameZipDirPath.$vFile['file_path'])){
                    unlink($gameZipDirPath.$vFile['file_path']);
                }
            }
        }
        $gamePath = Storage::path('public')."/game/";
        $files = scandir($gamePath);
        foreach ($files as $filex) {
            if ($filex !== '.' && $filex !== '..' && is_file($filex)) {
                // 删除历史文件
                unlink($gamePath.$filex);
            }
        }

        $saveGamePath = Storage::path('public/').$file['file_path'];
        $zip = new ZipArchive;
        if ($zip->open($saveGamePath) === true) {
            $zip->extractTo($gamePath); // 解压到指定目录
            $zip->close();
            return c_return(0,null);
        }
    }

    public function upload(Request $request){
        // 获取上传的文件
        $file = $request->file('file');

        $originalName = $file->getClientOriginalName();
        $ext = $file->getClientOriginalExtension();
        // 允许通过的后缀 配置
        $canUploadArr = [
            // 图片
            'zip',
        ];
        if(!in_array($ext,$canUploadArr)){
            cp_return(__('message.file_upload_error'));
        }

        // 生成文件夹
//        $dir = "images/news_files_" . date("Ymd");
        $dir = "game/zip";
        // 保存图片到临时目录
        try {
            $path = $file->store($dir, 'public');
            $fullPath = Storage::path('public/').$path; // 获取完整路径
            $insertData = [
                'file_real_name'=>$originalName,
                'file_ext'=>$ext,
                'file_path' => $dir. DIRECTORY_SEPARATOR.basename($fullPath),
                'file_name' => basename($fullPath),
                'created_at' => date("Y-m-d H:i:s",time())
            ];
            $fileModel = new File();
            $id = $fileModel->insertGetId($insertData);
            return c_return(0,[
                    'id' => $id
            ]);
//
//            if (file_exists($fullPath)) {
//                // 加载图片
//                $img = Image::make($fullPath);
//                // 压缩图片并保持原始比例
//                $img->resize(800, null, function ($constraint) {
//                    $constraint->aspectRatio(); // 保持纵横比
//                    $constraint->upsize(); // 防止图片放大
//                });
//                // 保存压缩后的图片
//                $img->encode('jpg', 75)->save($filePath);
//                unlink($fullPath);

//                return c_return(0,[
//                    'id' => $id
//                ]);
//            } else {
//                cp_return(__('message.file_upload_error'));
//            }
        } catch (\Exception $exception) {
            // 返回错误响应
            cp_return(__('message.file_upload_error'));
        }
    }

    public function download($id){
        $fileInfo = File::find($id);
        if(!$fileInfo){
            cp_return(__('message.file_download_error'));
        }
        return Storage::disk('public')->download($fileInfo['file_path'], $fileInfo['file_name']);
    }


    public function setListStyle(){
        $systemModel = new System();
        $type =  request()->post('type',1);
        if(!in_array($type,[1,2])){
            $type = 1;
        }
        try {
            $systemModel->where('id',1)->update([
                'list_type' => $type
            ]);
            return c_return(0,null);
        }catch (\Exception $exception){
            cp_return(__('message.op_error'));
        }
    }

    public function carouselImage(LbtAddRequest $request){
        $systemModel = new System();
        try {
            $systemModel->where('id',1)->update([
                'carousel_image_ids' => implode(',',$request->post('carousel_image_ids'))
            ]);
            return c_return(0,[
                'ids' => $request->post('carousel_image_ids')
            ]);
        }catch (\Exception $exception){
            cp_return(__('message.op_error'));
        }
    }

    public function setGameCarouseImage(){
        $data = \request()->only('games_carousel_image')['games_carousel_image'];
        $json = json_decode($data,true);
//        if(empty($json)){
//            cp_return(__('message.op_error'));
//        }
        if(count($json)>9){
            cp_return(__('message.op_error'));
        }

        $systemModel = new System();
        try {
            $systemModel->where('id',1)->update([
                'games_carousel_image' => $data
            ]);
            return c_return(0,null);
        }catch (\Exception $exception){
            cp_return(__('message.op_error'));
        }
    }

    public function getGameCarouseImage(){
        $systemModel = new System();
        $data = $systemModel->select(['games_carousel_image'])->where('id',1)->first();
        if(!empty($data)){
            $fmt = json_decode($data['games_carousel_image'],true);
        }
        return c_return(0,$fmt ?? []);

    }



    public function getConfig(){
        $systemModel = new System();
        $data = $systemModel->where('id',1)->first();
        if(!empty($data['carousel_image_ids'])){
            $data['carousel_image_ids'] = explode(',',  $data['carousel_image_ids']);
        }
        return c_return(0,$data);
    }

    public function getRegisterCode(){
        $code = md5(time()."zlhranhou");
        Redis::psetex('admin:register:code:'.$code, 24 * 60 * 60 * 1000, $code);
        return c_return(0,[
            'code' => $code
        ]);
    }

    public function register(){
        $code = request()->post('code','');
        $username = request()->post('username','');
        $pwd = request()->post('password','');
        if (!Redis::get('admin:register:code:'.$code)) {
            cp_return(__('message.auth_error'));
        }else{
            $userModel = new User();
            $userInfo = $userModel->where('username',$username)->first();
            if($userInfo){
                cp_return(__('message.register_error'));
            }
            $res =$userModel->insert(
                [
                    'username' => $username,
                    'pwd' => Hash::make($pwd),
                    'status' => 1
                ]
            );
            if($res){
                Redis::delete('admin:register:code:'.$code);
            }
            return c_return(0,[
                'id' => $res
            ]);
        }
    }

}
